import md5 from './md5'
import https from './https'

//域名地址
const host = https.host();

//授权参数设置
const env = https.env();

// 网页登录授权
const redirectURL = 'https://mh.thinkmongroup.com/yoush';
const appid = 'wxc24d4cd1b69e3c2b';

//文件服务器
const fileServerHost = https.fileServerHost();

export {
	host,
	fileServerHost,
	appid,
	redirectURL
}

//请求封装
function request(url, method, data, header = {}) {
	uni.showLoading({
		title: '加载中' //数据请求前loading
	})

	let headers = {
		'x-platform-id': 'CUSTOMER',
		//'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' // 默认值
		'content-type': 'application/json;charset=UTF-8' // 这里不用json
	}

	let accesstoken = getStorageAccesstoken();
	if (accesstoken) {
		headers['Authorization'] = `Bearer ${accesstoken}`
	}

	//标准授权数据
	let apihost = host + url;

	//微信请求方法，差异只有request与httpRequest的区别
	return new Promise((resolve, reject) => {
		uni.request({
			url: apihost, //仅为示例，并非真实的接口地址
			method: method,
			data: data,
			header: headers,
			success: function(res) {
				uni.hideLoading();
				/**
				 * 系统登录失败
				 */
				if (res.statusCode === 403) {
					uni.showToast({
						title: "系统登录失败",
						icon: "none",
						duration: 1500
					});
					//退出登录统一清除缓存方法
					quit();
					uni.navigateTo({
						url: "/apiPam/logincommon/main"
					});
				}
				resolve(res);
			},
			fail: function(error) {
				if (error.statusCode === 401) {
					//token过期了
				}
				
				console.info(error)

				// uni.navigateTo({
				// 	url: "/apiPam/login/main"
				// });

				reject(false)
			},
			complete: function() {
				uni.hideLoading();
			}
		})
	})
}

//不支持get，所以关闭
// export function get(url, data) {
//   return request(url, 'GET', data)
// }

export function post(url, data) {
	return request(url, 'POST', data)
}

export function get(url, data) {
	return request(url, 'GET', data)
}

export function put(url, data) {
	return request(url, 'PUT', data)
}

export function del(url, data) {
	return request(url, 'DELETE', data)
}

//@Author:  i@jinjiajin.net @DateTime:  2019-02-17 15:12:21
//api接口加密sign值md5处理
let CalcuMD5 = function(param) {
	let sign_basis = 'ANDYJJ' + assemble(param) + env.APP_SERECT;
	sign_basis = md5(sign_basis).toUpperCase();
	return sign_basis;
}

//@Author:  i@jinjiajin.net @DateTime:  2019-02-17 15:12:26
//api接口加密param值处理
let assemble = function(param) {
	let joint = '';
	if (typeof param == "object" && Object.getOwnPropertyNames(param).length > 0) {
		let arr = Object.getOwnPropertyNames(param);
		let arr1 = arr.sort();
		let i = '';
		for (i in arr1) {
			let val = param[arr1[i]];
			if (val == void 0 || val == '') {
				continue;
			}
			if (typeof val == "boolean") {
				let val = val ? 1 : 0;
			}
			val = (typeof val == "object" && Object.getOwnPropertyNames(val).length > 0) ? assemble(val) : val;
			joint += (arr1[i] + val);
		}
	}
	return joint;
}

//@Author:  i@jinjiajin.net @DateTime:  2019-02-17 15:12:31
//api接口加密所用时间处理
let process_date = function() {
	let now = new Date();
	let fullyear = now.getFullYear();
	let month = (now.getMonth() + 1) > 9 ? now.getMonth() + 1 : '0' + (now.getMonth() + 1);
	let day = now.getDate() > 9 ? now.getDate() : '0' + now.getDate();
	let hours = now.getHours() > 9 ? now.getHours() : '0' + now.getHours();
	let seconds = now.getSeconds() > 9 ? now.getSeconds() : '0' + now.getSeconds();
	let minutes = now.getMinutes() > 9 ? now.getMinutes() : '0' + now.getMinutes();
	return fullyear + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}



//----------------------------------------------常用方法 --------------------
//用户是否登录 未登录跳转到登录页面
export function toLogin() {
	let accesstoken = uni.getStorageSync('accesstoken');
	if (!accesstoken) {
		uni.navigateTo({
			url: "/apiPam/logincommon/main"
		});
	} else {
		return true;
	}
}

//获取openId
export function getStorageOpenid() {
	let openId = uni.getStorageSync("openId");
	if (openId) {
		return openId;
	} else {
		return ''
	}
}

//获取用户信息
export function getStorageUserInfo() {
	let userInfo = uni.getStorageSync("userInfo");
	if (userInfo) {
		return userInfo;
	} else {
		return ''
	}
}

//获取accesstoken
export function getStorageAccesstoken() {
	let accesstoken = uni.getStorageSync("accesstoken");
	if (accesstoken) {
		return accesstoken;
	} else {
		return ''
	}
}

//获取user_id
export function getStorageUserId() {
	let user_id = uni.getStorageSync("user_id");
	if (user_id) {
		return user_id;
	} else {
		return ''
	}
}

export function getStorageCartInfo() {
	let cart = uni.getStorageSync("cart")
	return cart
}

export function setStorageCartInfo(item) {
	if (item) {
		uni.setStorageSync("cart", item)
	}
}

export function getCartItemCounts() {
	let cart = getStorageCartInfo()
	console.info('cart=======')
	if (cart) {
		let number = 0
		cart.forEach(p => {
			number += p.num
		})

		uni.setTabBarBadge({
			index: 2,
			text: `${number}`
		})
	}
}

//获取平台
export function getStoragePlatform() {
	// #ifdef H5
	let platform = 'H5';
	// #endif
	// #ifdef APP-PLUS
	let platform = 'APP-PLUS';
	// #endif
	// #ifdef MP-WEIXIN
	let platform = 'MP-WEIXIN';
	// #endif
	// #ifdef MP-ALIPAY
	let platform = 'MP-ALIPAY';
	// #endif
	// #ifdef MP-BAIDU
	let platform = 'MP-BAIDU';
	// #endif
	// #ifdef MP-TOUTIAO
	let platform = 'MP-TOUTIAO';
	// #endif
	// #ifdef MP-QQ
	let platform = 'MP-QQ';
	// #endif
	return platform;
}

// 退出清除相应数据  -- 防止清除一些不需要清除的数据
export function quit() {
	uni.clearStorageSync();
	uni.setStorageSync("launchFlag", true);
}
//----------------------------------------------常用方法 --------------------

function formatNumber(n) {
	const str = n.toString()
	return str[1] ? str : `0${str}`
}

export function number_format(number, decimals, dec_point, thousands_sep) {
	decimals = decimals || 0; //这里默认设置保留两位小数，也可以注释这句采用传入的参数
	/*
	 3     * 参数说明：
	 4     * number：要格式化的数字
	 5     * decimals：保留几位小数
	 6     * dec_point：小数点符号
	 7     * thousands_sep：千分位符号
	 8     * */
	number = (number + '').replace(/[^0-9+-Ee.]/g, '');
	var n = !isFinite(+number) ? 0 : +number,
		prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
		sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
		dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
		s = '',
		toFixedFix = function(n, prec) {
			var k = Math.pow(10, prec);
			return '' + Math.ceil(n * k) / k;
		};
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	var re = /(-?\d+)(\d{3})/;
	while (re.test(s[0])) {
		s[0] = s[0].replace(re, "$1" + sep + "$2");
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}

export function formatDate(date) {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const t1 = [year, month, day].map(formatNumber).join('-')
	return `${t1}`
}

export function formatTime(date) {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()

	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	const t1 = [year, month, day].map(formatNumber).join('/')
	const t2 = [hour, minute, second].map(formatNumber).join(':')

	return `${t1} ${t2}`
}
